package logic

import (
	"context"
	"database/sql"
	"errors"
	"module_demo/user-service/model"
	"strconv"

	"module_demo/user-service/rpc/internal/svc"
	"module_demo/user-service/rpc/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserLogic {
	return &GetUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserLogic) GetUser(in *user.IdRequest) (*user.UserResponse, error) {

	id, err := strconv.Atoi(in.GetId())
	if err != nil {
		return nil, errors.New("参数错误")
	}

	userModel := model.NewUserModel(l.svcCtx.Mysql)
	u, err := userModel.FindOne(l.ctx, int64(id))
	if err != nil && (errors.Is(err, model.ErrNotFound) || errors.Is(err, sql.ErrNoRows)) {
		return nil, errors.New("参数错误")
	}
	if err != nil {
		l.Logger.Error("查询用户失败=", err)
		return nil, errors.New("参数错误")
	}

	return &user.UserResponse{
		Id:           strconv.FormatInt(u.Id, 10),
		Username:     u.Username.String,
		RegisterTime: u.RegisterTime.Format("2006-01-02 15:04:05"),
	}, nil
}
